package com.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.log4j.Logger;

public class JasperUtil {
	
	private static Logger log = Logger.getLogger(JasperUtil.class);
	
	public File JasperReportGenerator(String jrxmlFilename, Map<String, Object> parameters, JRBeanCollectionDataSource colDataSource) {
		
		File destFile = null;
		
		try{
			
		String jasperPath = ((ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext()).getRealPath("/");
			
		File jrxmlFile = new File(jasperPath + "/jasper/" + jrxmlFilename);
		InputStream jrxmlInputStream = new FileInputStream(jrxmlFile);
		
		String fileName = jrxmlFile.getName();
		
		String destFilename = jasperPath + "/jasper/" + fileName + ".pdf";
		destFile = new File(destFilename);
		
		JasperDesign jasperDesign = JRXmlLoader.load(jrxmlInputStream);
		JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, colDataSource);
		
		JasperExportManager.exportReportToPdfFile(jasperPrint, destFilename);
		
		}catch (JRException jre){
			log.error("Exception in Jasper Reporting Generator", jre);
		}catch (FileNotFoundException fnfe){
			log.error("Exception in Jasper Reporting Generator, jrxml file not found", fnfe);
		}
		
		return destFile;
	}

}
